package com.cmsz.uregs.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.cmsz.uregs.dao.AdminDao;
import com.cmsz.uregs.entity.Admin;

@Repository
public class AdminDaoImpl implements AdminDao {

	@PersistenceContext
	private EntityManager em;

	@Override
	public Admin addAdmin(Admin admin) {
		em.persist(admin);
		return admin;
	}

	@Override
	public void updateAdmin(Admin admin) {
		Admin adminManaged = em.find(Admin.class, admin.getId());
		adminManaged.setName(admin.getName());
		adminManaged.setPassword(admin.getPassword());
		adminManaged.setQx(admin.getQx());
		em.persist(adminManaged);

	}

	@Override
	public void deleteAdmin(int id) {
		Admin admin = em.find(Admin.class, id);
		em.remove(admin);
	}

	@Override
	public List<Admin> findAllAdmins() {
		String jpql = "from Admin";
		return em.createQuery(jpql, Admin.class).getResultList();
	}

	@Override
	public Admin findAdmin(int id) {
		return em.find(Admin.class, id);
	}

	@Override
	public Admin findAdminByName(String username) {
		String jpql = "from Admin u where u.username=:username";
		List<Admin> admins = em.createQuery(jpql, Admin.class)
				.setParameter("username", username).getResultList();
		return admins.size() > 0 ? admins.get(0) : null;
	}
}
